import { FC, useEffect, useRef, useState } from 'react'
import Taro, { useDidShow } from '@tarojs/taro'
import pic from '../../resource/pic.png'
import arrowTop from '../../resource/arrow-top.png'
import arrowBottom from '../../resource/arrow-bottom.png'
import style from './style.less'
import { Picker, ScrollView } from '@tarojs/components'
import CargoSource from './components/CargoSource'

const Index: FC = () => {
  const [token, setToken] = useState(() => Taro.getStorageSync('token'))
  const [auth, setAuth] = useState(() => Taro.getStorageSync('auth'))
  const [vip, setVip] = useState(() => Taro.getStorageSync('vip'))
  const [refreshing, setRefreshing] = useState(false)
  const [flag, setFlag] = useState(0)

  const [start, setStart] = useState('装货地')
  const startPos = useRef('')
  const [end, setEnd] = useState('卸货地')
  const endPos = useRef('')
  const [sort, setSort] = useState('时间排序')
  const sortType = useRef(0)
  const sortRef = useRef(['时间排序', '运费排序', '距离排序'])

  const [list, setList] = useState<any[]>([])

  const pageNum = useRef(1)
  const pageSize = useRef(10)

  const [scrollTop, setScrollTop] = useState(-1)


  useEffect(() => {
    getListReq()
  }, [])

  useDidShow(() => {
    setToken(() => Taro.getStorageSync('token'))
    setAuth(() => Taro.getStorageSync('auth'))
    setVip(() => Taro.getStorageSync('vip'))
  })

  const getListReq = (loadAddress = '', unloadAddress = '', sort = 0, pageNum = 1, pageSize = 10) => {
    Taro.showLoading({ title: '加载中' })
    Taro.request({
      url: 'http://139.9.123.88:8082/fta-cargo/currentCargo/carrierQueryCurrentCargo',
      method: 'POST',
      data: JSON.stringify({
        openId: Taro.getStorageSync('token'),
        loadAddress,
        pageNum,
        pageSize,
        unloadAddress,
        sort
      }),
      success: (data) => {
        if (pageNum === 1) {
          setScrollTop(0)
        }
        console.log('货源大厅', data);
        Taro.hideLoading()
        setList(data.data.data.list)
        setRefreshing(false)
      },
      fail: () => {
        Taro.hideLoading()
        setRefreshing(false)
      }
    })
  }

  const navSelect = (num) => {
    setFlag(num)
  }

  const changeRegion = (e, num) => {
    setScrollTop(-1)
    pageNum.current = 1
    if (num === 0) {
      setFlag(0)
      if (e.detail.value[0] === '不限') {
        startPos.current = ''
        getListReq(startPos.current, endPos.current, sortType.current, pageNum.current, pageSize.current)
        setStart('不限')
        return
      }
      if (e.detail.value[1] === '不限') {
        startPos.current = e.detail.value[0]
        getListReq(startPos.current, endPos.current, sortType.current, pageNum.current, pageSize.current)
        setStart(e.detail.value[0])
        return
      }
      if (e.detail.value[2] === '不限') {
        startPos.current = e.detail.value[0] + '-' + e.detail.value[1]
        getListReq(startPos.current, endPos.current, sortType.current, pageNum.current, pageSize.current)
        setStart(e.detail.value[1])
        return
      }
      startPos.current = e.detail.value[0] + '-' + e.detail.value[1] + '-' + e.detail.value[2]
      getListReq(startPos.current, endPos.current, sortType.current, pageNum.current, pageSize.current)
      setStart(e.detail.value[1] + e.detail.value[2])
    } else if (num === 1) {
      setFlag(0)
      if (e.detail.value[0] === '不限') {
        endPos.current = ''
        getListReq(startPos.current, endPos.current, sortType.current, pageNum.current, pageSize.current)
        setEnd('不限')
        return
      }
      if (e.detail.value[1] === '不限') {
        endPos.current = e.detail.value[0]
        getListReq(startPos.current, endPos.current, sortType.current, pageNum.current, pageSize.current)
        setEnd(e.detail.value[0])
        return
      }
      if (e.detail.value[2] === '不限') {
        endPos.current = e.detail.value[0] + '-' + e.detail.value[1]
        getListReq(startPos.current, endPos.current, sortType.current, pageNum.current, pageSize.current)
        setEnd(e.detail.value[1])
        return
      }
      endPos.current = e.detail.value[0] + '-' + e.detail.value[1] + '-' + e.detail.value[2]
      getListReq(startPos.current, endPos.current, sortType.current, pageNum.current, pageSize.current)
      setEnd(e.detail.value[1] + e.detail.value[2])
    }
    setFlag(0)
  }

  const bindScrollToRefresh = () => {
    setRefreshing(true)
    pageNum.current = 1
    getListReq(startPos.current, endPos.current, sortType.current, pageNum.current, pageSize.current)
  }

  const bindScrollToLower = () => {
    pageNum.current += 1
    getListReq(startPos.current, endPos.current, sortType.current, pageNum.current, pageSize.current)
  }

  const handleSort = () => {
    navSelect(3)
    Taro.showActionSheet({
      itemList: sortRef.current,
      success: function (res) {
        setScrollTop(-1)
        pageNum.current = 1
        console.log(res.tapIndex)
        setSort(sortRef.current[res.tapIndex])
        sortType.current = res.tapIndex
        getListReq(startPos.current, endPos.current, sortType.current, pageNum.current, pageSize.current)
        setFlag(0)
      },
      fail: function (res) {
        console.log(res.errMsg)
        setFlag(0)
      }
    })
  }

  return (
    <div className={style.root}>
      <div className="navContainer">
        <div className="navItem" style={{ color: flag === 1 ? '#f18340' : '#000' }} onClick={() => { navSelect(1) }}>
          <Picker mode='region' value={[]} customItem='不限' onChange={(e) => { changeRegion(e, 0) }} onCancel={() => { setFlag(0) }}>
            {start}
            <img src={flag === 1 ? arrowTop : arrowBottom} alt="" />
          </Picker>
        </div>
        <div className="navItem" style={{ color: flag === 2 ? '#f18340' : '#000' }} onClick={() => { navSelect(2) }}>
          <Picker mode='region' value={[]} customItem='不限' onChange={(e) => { changeRegion(e, 1) }} onCancel={() => { setFlag(0) }}>
            {end}
            <img src={flag === 2 ? arrowTop : arrowBottom} alt="" />
          </Picker>
        </div>
        <div className="navItem" style={{ color: flag === 3 ? '#f18340' : '#000' }} onClick={() => { handleSort() }}>
          {sort}
          <img src={flag === 3 ? arrowTop : arrowBottom} alt="" />
        </div>
      </div>
      <ScrollView
        className="goodsList"
        scrollY
        scrollTop={scrollTop}
        scroll-with-animation="true"
        lowerThreshold={5}
        refresherEnabled
        refresherBackground='#f5f5f5'
        refresherTriggered={refreshing}
        onRefresherRefresh={bindScrollToRefresh}
        onScrollToLower={bindScrollToLower}
      >
        {list.length ? list?.map(item => {
          return (
            <div key={item.cargoId}>
              <CargoSource info={{ ...item }} />
            </div>
          )
        }) : <img src={pic} alt="" className="bgi" />}
      </ScrollView>
    </div>
  )
}

export default Index